import { Controller, Post, Delete, Get, Query, UploadedFile, UseInterceptors, Body } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { OssService } from './oss.service';

@Controller('oss')
export class OssController {
  constructor(private readonly ossService: OssService) { }

  /**
   * 上传单个文件
   * @param file 上传的文件
   * @param folder 可选的存储文件夹
   * @returns 上传结果
   */
  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  async upload(
    @UploadedFile() file,
    @Body('folder') folder?: string,
  ) {
    const key = folder
      ? `${folder}/${Date.now()}-${file.originalname}`
      : `${Date.now()}-${file.originalname}`;

    return this.ossService.uploadFile(key, file.buffer, file.mimetype);
  }

  /**
   * 删除文件
   * @param key 要删除的文件key
   * @returns 删除结果
   */
  @Delete('delete')
  async delete(@Query('key') key: string) {
    return {
      success: await this.ossService.deleteFile(key),
      message: '文件已删除'
    };
  }

  /**
   * 列出文件
   * @param prefix 可选的前缀
   * @param maxKeys 最大数量
   * @returns 文件列表
   */
  @Get('list')
  async list(
    @Query('prefix') prefix?: string,
    @Query('maxKeys', { transform: (v) => parseInt(v) }) maxKeys = 100,
  ) {
    const result = await this.ossService.listFiles(prefix, maxKeys);

    // 为每个文件添加访问URL
    if (result.Contents) {
      result.Contents = result.Contents.map(item => ({
        ...item,
        url: this.ossService.getFileUrl(item.Key)
      }));
    }

    return result;
  }

  /**
   * 获取文件URL
   * @param key 文件key
   * @returns 文件URL
   */
  @Get('url')
  getUrl(@Query('key') key: string) {
    return {
      url: this.ossService.getFileUrl(key)
    };
  }
}
